package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.dto.EntryDto;
import com.heima.behavior.entity.ApBehaviorEntry;
import com.heima.behavior.mapper.ApBehaviorEntryMapper;
import com.heima.behavior.service.IApBehaviorEntryService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * <p>
 * APP行为实体表,一个行为实体可能是用户或者设备，或者其它 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-03-17
 */


@Service
public class ApBehaviorEntryServiceImpl extends ServiceImpl<ApBehaviorEntryMapper, ApBehaviorEntry> implements IApBehaviorEntryService {

    @Override
    public ApBehaviorEntry getEntry(EntryDto dto) {
        // 判断用户id不为空,则是使用用户登录
        if (dto.getUserId() != null) {
            // 根据用户id和类型为1 查询实体记录
            LambdaQueryWrapper<ApBehaviorEntry> query = new LambdaQueryWrapper<>();
            query.eq(ApBehaviorEntry::getType, 1);
            query.eq(ApBehaviorEntry::getEntryId, dto.getUserId().toString());
            ApBehaviorEntry behaviorEntry = this.getOne(query);
            if (behaviorEntry != null) {
                return behaviorEntry;
            } else {
                // 新增行为实体
                ApBehaviorEntry apBehaviorEntry = new ApBehaviorEntry();
                apBehaviorEntry.setType(1);
                apBehaviorEntry.setEntryId(dto.getUserId().toString());
                apBehaviorEntry.setCreatedTime(new Date());
                this.save(apBehaviorEntry);
                return apBehaviorEntry;
            }
        }
        // 设备id不为空,是使用设备登录
        if (!StringUtils.isEmpty(dto.getEquipmentId())) {
            // 根据设备id和类型为0 查询实体记录
            LambdaQueryWrapper<ApBehaviorEntry> query = new LambdaQueryWrapper<>();
            query.eq(ApBehaviorEntry::getType, 0);
            query.eq(ApBehaviorEntry::getEntryId, dto.getEquipmentId());
            ApBehaviorEntry behaviorEntry = this.getOne(query);
            if (behaviorEntry != null) {
                return behaviorEntry;
            } else {
                // 新增行为实体
                ApBehaviorEntry apBehaviorEntry = new ApBehaviorEntry();
                apBehaviorEntry.setType(0);
                apBehaviorEntry.setEntryId(dto.getEquipmentId());
                apBehaviorEntry.setCreatedTime(new Date());
                this.save(apBehaviorEntry);
                return apBehaviorEntry;
            }
        }
        return null;
    }
}


